const dao = require('./base');

module.exports = {

    caList: async function (condition, fields = "*", by = []) {
        let sql = `SELECT ${fields} from afc_ca_view where del_flag=0`;
        let pre = [];
        if (condition.ca_name !== undefined && condition.ca_name !== '') {
            sql += ` and ca_name like %?%`;
            pre.push(condition.ca_name);
        }
        sql = dao.by(sql, by);

        let limit = dao.limit(sql, condition, pre);
        sql = limit.sql;
        pre = limit.pre;

        let data;
        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    caAdd: async function (fields = []) {
        let sql = "insert into afc_ca (ca_name,ca_department,ca_address,mid,pid) values(?,?,?,?,?)";
        let pre = [];
        let data;
        pre.push(fields.ca_name);
        pre.push(fields.ca_department);
        pre.push(fields.ca_address);
        pre.push(fields.mid);
        pre.push(fields.pid);
        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },

    caUpdate: async function (condition = {}, fields = {}) {
        let sql = "update afc_ca set ";
        let pre = [];
        let data;

        if (fields.ca_name !== undefined && fields.ca_name !== '') {
            sql = dao.update_sql_splice(sql, "ca_name");
            pre.push(fields.ca_name);
        }
        if (fields.ca_department !== undefined && fields.ca_department !== '') {
            sql = dao.update_sql_splice(sql, "ca_department");
            pre.push(fields.ca_department);
        }
        if (fields.ca_address !== undefined && fields.ca_address !== '') {
            sql = dao.update_sql_splice(sql, "ca_address");
            pre.push(fields.ca_address);
        }
        if (fields.mid !== undefined && fields.mid !== '') {
            sql = dao.update_sql_splice(sql, "mid");
            pre.push(fields.mid);
        }
        if (fields.pid !== undefined && fields.pid !== '') {
            sql = dao.update_sql_splice(sql, "pid");
            pre.push(fields.pid);
        }
        if (fields.del_flag !== undefined && fields.del_flag !== '') {
            sql = dao.update_sql_splice(sql, "del_flag");
            pre.push(fields.del_flag);
        }
        if (condition.ca_id !== undefined && condition.ca_id !== '') {
            sql += ` where ca_id = ?`;
            pre.push(condition.ca_id);
        }
        await dao.query(sql, pre).then((results, fields) => {
            data = results;
        }).catch((err) => {
            data = {err: err}
        });
        return data;
    },


};
